package com.byq.ai.agentlab.service;

import com.byq.ai.agentlab.entity.Task;
import com.byq.ai.agentlab.entity.TaskStatus;
import com.byq.ai.agentlab.repository.TaskRepository;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class TaskService {
    private static final Logger logger = LoggerFactory.getLogger(TaskService.class);
    
    private final TaskRepository taskRepository;
    private final ObjectMapper objectMapper;
    private final EmbeddingService embeddingService;

    @Autowired
    public TaskService(TaskRepository taskRepository, ObjectMapper objectMapper, EmbeddingService embeddingService) {
        this.taskRepository = taskRepository;
        this.objectMapper = objectMapper;
        this.embeddingService = embeddingService;
        logger.info("TaskService initialized with TaskRepository: {}", taskRepository);
    }

    public Task createTask(String name, String description, String collaborationPlan) {
        logger.info("Creating task: {}", name);
        Task task = new Task();
        task.setName(name);
        task.setDescription(description);
        task.setCollaborationPlan(collaborationPlan);
        task.setStatus(TaskStatus.PENDING);
        
        // Generate embedding for the task description
//        float[] embedding = embeddingService.generateEmbedding(description);
//       task.setEmbedding(embedding);
        
        Task savedTask = taskRepository.save(task);
        logger.info("Task created with ID: {}", savedTask.getTaskId());
        return savedTask;
    }

    public Task getTask(Long taskId) {
        logger.info("Getting task with ID: {}", taskId);
        return taskRepository.findById(taskId)
                .orElseThrow(() -> new RuntimeException("Task not found with ID: " + taskId));
    }

    public List<Task> findSimilarTasks(String query, int limit) {
        logger.info("Finding similar tasks for query: {}", query);
        float[] queryEmbedding = embeddingService.generateEmbedding(query);
        return taskRepository.findSimilarTasks(queryEmbedding, limit);
    }

    public Task updateTaskStatus(Long taskId, TaskStatus status) {
        logger.info("Updating task status for ID: {} to: {}", taskId, status);
        Task task = getTask(taskId);
        task.setStatus(status);
        return taskRepository.save(task);
    }
} 